﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Resto.CostControl.Core.Models;
using QuickApp.Core;
using QuickApp.MVCControl.Tree;
using Resto.CostControl.Core.Models.SysSettings;
using Resto.CostControl.Core;
using QuickApp.MVCControl;
using QuickApp.MVCControl.Form;

namespace Resto.CostControl.Web.Controllers
{
    public class DishRangeController : Controller
    {
        private readonly IRepository<DishRange> _Repo;
        private readonly IUnitOfWork _UnitOfWork;
        public DishRangeController(IRepository<DishRange> repo, UnitOfWork unitOfWork)
        {
            _Repo = repo;
            _UnitOfWork = unitOfWork;
        }
        
        public ActionResult Index()
        {
            ViewBag.DefaultDate = DateTime.Now.AddDays(7).ToString("yyyy-MM-dd");
           // ViewBag.AddWeekNum = 0.00;
            ViewBag.WeekList = GetWeekDataSource();
            return View();
        }

        private double CurrentWeek = 0;

        [Ninject.Inject]
        public IRepository<EnumItem> ItemRepo { get; set; }
        [HttpPost]
        public JsonResult Tree(string type, string datetime = null)
        {
            var nodes = new List<JsonTreeNode>();
            var weeks = ItemRepo.FindAll(item => item.TypeCode == "Week").OrderBy(item => item.SeqNo).Select(item => new { item.EnumCode, item.EnumName });

            var CurrentDate = DateTime.Now.AddDays(7);
            if (!string.IsNullOrEmpty(datetime))
            {
                CurrentDate = Convert.ToDateTime(datetime);
            }
            var dayOfWeek = (double)CurrentDate.DayOfWeek;
            foreach (var week in weeks)
            {
                dayOfWeek = dayOfWeek == 0 ? 7 : dayOfWeek;
                var date = CurrentDate.AddDays(double.Parse(week.EnumCode) - dayOfWeek).ToString("yyyy-MM-dd");

                var node = new JsonTreeNode();
                node.id = date;
                node.text = date + string.Format("（{0}）", week.EnumName);
                node.value = date + string.Format("（{0}）", week.EnumName);
                node.isexpand = true;
                node.showcheck = false;
                node.complete = true;
                node.hasChildren = true;
                nodes.Add(node);
            }
            return Json(nodes);
        }

        [HttpPost]
        public JsonResult ChooseTree(double AddWeekNum)//选择周，AddWeekNum为在当前周上增加几周，负数为减去几周
        {
            
            var nodes = new List<JsonTreeNode>();
            var weeks = ItemRepo.FindAll(item => item.TypeCode == "Week").OrderBy(item => item.SeqNo).Select(item => new { item.EnumCode, item.EnumName });
            var CurrentDate = DateTime.Now.AddDays(7 + AddWeekNum*7);
            var dayOfWeek = (double)CurrentDate.DayOfWeek;
            foreach (var week in weeks)
            {
                dayOfWeek = dayOfWeek == 0 ? 7 : dayOfWeek;
                var date = CurrentDate.AddDays(double.Parse(week.EnumCode) - dayOfWeek).ToString("yyyy-MM-dd");

                var node = new JsonTreeNode();
                node.id = date;
                node.text = date + string.Format("（{0}）", week.EnumName);
                node.value = date + string.Format("（{0}）", week.EnumName);
                node.isexpand = true;
                node.showcheck = false;
                node.complete = true;
                node.hasChildren = true;
                nodes.Add(node);
            }

            return Json(nodes);
        }

        //[HttpPost]
        //public JsonResult ChooseProWeek()//往上一周
        //{
        //    CurrentWeek -= 1;
        //    return ChooseTree(CurrentWeek);            
        //}

        //[HttpPost]
        //public JsonResult ChooseNextWeek()//往上一周
        //{
        //    CurrentWeek += 1;
        //    return ChooseTree(CurrentWeek);            
        //}

        [HttpPost]
        public JsonResult List(string type, DWZPageInfo pager, DWZQueryModel where)
        {
            // 添加ParentId的检索条件
            if (!string.IsNullOrWhiteSpace(type))
            {
                where.AddItem("Date", type);
            }
            else
            {
                where.AddItem("Date", DateTime.Now.ToString("yyyy-MM-dd"));
            }

            // 分页查询数据
            var list = _Repo.GetPageable(pager.ToPageInfo(), where);
            var fdata = pager.ToFlexiGridData<DishRange>(list.Page.ToList(), list.Total);

            return Json(fdata);
        }

        [HttpPost]
        public JsonResult Save(DateTime date, IList<Dish> dishList)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    if (dishList != null)
                    {
                        foreach (var d in dishList)
                        {
                            if (_Repo.Find(r => r.Date == date && r.DishId == d.Id) == null)
                            {
                                var range = new DishRange();
                                range.Id = Guid.NewGuid().ToString();
                                range.DishId = d.Id;
                                range.Code = d.Code;
                                range.Name = d.Name;
                                range.Category = d.Category;
                                range.DishCost = d.Cost;
                                range.DishPrice = d.Price;
                                range.Date = date;

                                _Repo.Insert(range);
                            }
                        }
                    }

                    _UnitOfWork.Commit();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

            var result = new JsonReturnMessages
            {
                IsSuccess = true,
                Msg = "操作成功",
            };
            return Json(result);
        }

        [HttpPost]
        public JsonResult Delete(string Id)
        {
            JsonReturnMessages msg = new JsonReturnMessages();
            if (!string.IsNullOrEmpty(Id))
            {
                try
                {
                    _Repo.Delete(Id);
                    _UnitOfWork.Commit();
                    msg.IsSuccess = true;
                    msg.Msg = "操作成功";
                }
                catch (Exception ex)
                {
                    msg.IsSuccess = false;
                    msg.Msg = "操作失败:" + ex.Message;
                }
            }
            else
            {
                msg.IsSuccess = false;
                msg.Msg = "参数错误";
            }
            return Json(msg);
        }

        public List<SelectListItem> GetWeekDataSource()
        {
            var date = DateTime.Now;
            var year = date.Year;
            var items = new List<SelectListItem>();
            var weeks = CommonController.GetWeekAmount(year);
            var curweek = CommonController.GetWeekOfYear(date);
            for (var i = 1; i <= weeks; i++)
            {
                var startDay = CommonController.GetWeekDay(year, i, 1);
                var endDay = CommonController.GetWeekDay(year, i, 7);
                items.Add(new SelectListItem
                {
                    Text = "(" + i.ToString().PadLeft(2, '0') + "周)" + startDay.ToString("MM-dd") + "—" + endDay.ToString("MM-dd"),
                    Value = Url.Action("Index", new { week = i, day = startDay.ToString("yyyy-MM-dd") }),
                });
            }
            return items;
        }
    }
}
